package hammersmith.local.management;

import hammersmith.local.valueobjects.Article;
import hammersmith.local.valueobjects.Log;
import hammersmith.local.valueobjects.Person;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;

public class LogManagement implements Serializable {

	private static final long serialVersionUID = -4724755072498909459L;

	private ArrayList<Log> logList;

	public ArrayList<Log> getLogList() {
		if (this.logList == null) {
			this.logList = new ArrayList<Log>();
			return this.logList;
		} else {
			return this.logList;
		}
	}

	public void setLogList(ArrayList<Log> logList) {
		this.logList = logList;
	}

	public LogManagement() {
		this.logList = new ArrayList<Log>();
	}

	public Log addLog(Person p, Article a, int stock, String type) {
		Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
		Log log = new Log(p, a, timeStamp.toString(), stock, type);
		this.logList.add(log);
		return log;
	}
	
	public boolean isBetween(Date d1, Date d2) {
		if (d1.getTime() > d2.getTime()) {
			return true;
		} else {
			return false;
		}
	}

	public ArrayList<Log> getLogsByArticle(Article article) {
		ArrayList<Log> foundedLogs = new ArrayList<Log>();

		for (Log log : this.logList) {
			if (log.getArticle() == article) {
				foundedLogs.add(log);
			}
		}
		return foundedLogs;
	}

	public int stockChangePerDay(Timestamp begin, ArrayList<Log> list, int stock, Article a) {

		// Aktueller Bestand des Artikels ist stock!

		Date day = new Date(begin.getTime());
		Date dayBefore = new Date(day.getTime() - 24 * 3600 * 1000);

		// Logger durchlaufen
		// beginnend mit dem letzten Log vom Artikel
		for (int i = list.size() - 1; i >= 0; i--) {

			Log l = list.get(i);

			Timestamp t = Timestamp.valueOf(l.getTimestamp());
			Date timeOfLog = new Date(t.getTime());

			if (isBetween(timeOfLog, dayBefore)) {

				if (l.getWhat().equals("hinzugefuegt")
						|| l.getWhat().equals("veraendert")) {
					// setzen
					stock = l.getCount();

				} else {
					// gekauft und geloescht
					stock += l.getCount();
				}
			}
		}
		
		if(a.getCreateDate().after(dayBefore)){
			stock=0;
		}
		return stock;
	}
	
	public int[] getLogByArticleAndDays(Article a, int days) {

		ArrayList<Log> logList = getLogsByArticle(a);
		Timestamp ts = new Timestamp(System.currentTimeMillis());
		int[] stockPerDay = new int[days+1];
		stockPerDay[0] = a.getStock();

		int stock = a.getStock();

		for (int i = 1; i <= days; i++) {
			stock = stockChangePerDay(ts, logList, stock, a);
			stockPerDay[i] = stock;

			long timeInMillis = ts.getTime();
			Date dayBefore = new Date(timeInMillis - 24 * 3600 * 1000);
			ts = new Timestamp(dayBefore.getTime());
			
			System.out.println(stock);

		}
		return stockPerDay;
	}

}
